<template>
  <div class="card" style="width: 50%;padding: 20px">

    <el-form ref="formRef" :rules="data.rules" :model="data.form"  label-width="80px" style="padding-right: 40px;padding-top: 20px">

      <el-form-item label="头像" prop="avatar">
          <el-upload
              ref="uploadRef"
              class="avatar-uploader"
              action="http://localhost:9090/file/upload"
              :auto-upload="true"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :headers="{Authorization:uploadToken.token}"
          >

            <img v-if="data.form.avatar" :src="data.form.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>

      </el-form-item>

      <el-form-item label="账号" prop="username">
        <el-input disabled size="large" v-model="data.form.username" placeholder="请输入账号" autocomplete="off"></el-input>
      </el-form-item>

      <el-form-item label="姓名" prop="name">
        <el-input  size="large" v-model="data.form.name" placeholder="请输入姓名" autocomplete="off"></el-input>
      </el-form-item>

      <el-form-item label="电话" prop="phone">
        <el-input size="large" v-model="data.form.phone" placeholder="请输入电话" autocomplete="off"></el-input>
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input size="large" v-model="data.form.email" placeholder="请输入邮箱" autocomplete="off"></el-input>
      </el-form-item>


      <div style="display:flex;justify-content: center;">
        <el-button size="large" style="width: 30%" type="primary" @click="updateUser">更新</el-button>
        <el-button size="large" style="width: 30%" type="primary" @click="handleUpdatePassword">修改密码</el-button>
      </div>



    </el-form>

    <el-dialog title="修改密码" v-model="data.formVisible1" width="500">
      <el-form ref="formRef" :rules="data.rules" :model="data.form" style="padding-right: 50px;padding-top: 20px">
        <el-form-item  prop="password" label="原密码" label-width="100px">
          <el-input show-password v-model="data.form.password" placeholder="请输入原密码" autocomplete="off"/>
        </el-form-item>
        <el-form-item prop="newPassword" label="新密码" label-width="100px">
          <el-input show-password v-model="data.form.newPassword" placeholder="请输入新密码" autocomplete="off"/>
        </el-form-item>
        <el-form-item prop="rePassword" label="确认新密码" label-width="100px">
          <el-input show-password v-model="data.form.rePassword" placeholder="请再次输入新密码" autocomplete="off" />
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.formVisible1=false">取消</el-button>
          <el-button type="primary" @click="savePassword">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {reactive,ref} from "vue";
import request from "../utils/request";
import {ElMessage} from "element-plus";
import {useTokenStore} from "../stores/token";
const uploadToken = useTokenStore();
const formRef=ref()

const handleAvatarSuccess = (res) => {
  console.log('后台上传的数据1',res)
  console.log('文件大小:',res.size/1024/1024,'MB','上传成功：',res.data)
  data.form.avatar = res.data
}


const beforeAvatarUpload = (res) => {

 if (res.size / 1024 / 1024 > 1) {
    ElMessage.error('图片大小不能超过 1MB!')
    return false
  }
  return true
}

const validatePass = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请再次确认密码'))
  } else if (value !== data.form.newPassword){
    callback(new Error('两次输入的密码不一致!'))
  } else {
    callback()
  }

}
const data=reactive({
  formVisible1:false,
  user:JSON.parse(localStorage.getItem('localStorageUser')),
  form:{},
  rules:{
    username:[{required:true,message:'请输入账号',trigger:'blur'}],
    name:[{required:true,message:'请输入姓名',trigger:'blur'}],
    phone:[{required:true,message:'请输入电话',trigger:'blur'}],
    email:[{required:true,message:'请输入邮箱',trigger:'blur'}],
    password:[
      {required:true,message:'请输入密码',trigger:'blur'},
      { min: 5, max: 11, message: '长度在 5 到 11 个字符', trigger: 'blur' }
    ],
    newPassword:[
        {required:true,message:'请输入新密码',trigger:'blur'},
      { min: 5, max: 11, message: '长度在 5 到 11 个字符', trigger: 'blur' }
    ],
    rePassword:[{validator:validatePass,required:true,trigger:'blur'}]
  }
})

const emit=defineEmits(['updateUser'])

if (data.user.role==='owner'){
  request.get('/owner/selectById/' + data.user.id).then(res=>{
    data.form = res.data
})
}else {
  data.form = data.user
}

const handleUpdatePassword=()=>{
  data.form.password="",
  data.form.newPassword="",
  data.form.rePassword=""
  data.formVisible1=true
}

const savePassword=()=>{
  data.form.id = data.user.id
  data.form.role = data.user.role

  formRef.value.validate((valid) => {
    if (valid){

        request.put('/web/updatePassword', data.form).then(res =>{
          if (res.code === '200'){
            ElMessage.success('操作成功')
            localStorage.removeItem('localStorageUser')
            setTimeout(()=>{
              location.href = '/login'
            },500)
          }else {
            ElMessage.error(res.msg)
          }
        })
      }


})



}

const updateUser=()=>{
  if (data.user.role==='owner'){
    request.put('/owner/update', data.form).then(res=>{
        if (res.code==='200'){
          ElMessage.success('更新成功')
          //更新缓存数据
          localStorage.setItem('localStorageUser',JSON.stringify(data.form))
          //触发父级从缓存里拿到的数据
          emit('updateUser')
        }else {ElMessage.error(res.msg)}

    })
  }else if (data.user.role==='admin'){
    request.put('/admin/update', data.form).then(res=>{
      if (res.code==='200'){
        ElMessage.success('更新成功')
        //更新缓存数据
        localStorage.setItem('localStorageUser',JSON.stringify(data.form))
        //触发父级从缓存里拿到的数据
        emit('updateUser')
      }else {ElMessage.error(res.msg)}

    })
  }
}

</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>